﻿using AiXiu.BLL;
using AiXiu.Common;
using AiXiu.IBLL;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace AiXiu.WebSite
{
    public class Global : HttpApplication
    {
        protected async void Application_Start(object sender, EventArgs e)
        {
            //启用日志记录
            FileInfo fileInfo = new FileInfo(Server.MapPath("~/log4net.config"));
            log4net.Config.XmlConfigurator.Configure(fileInfo);

            //LogHelper.Info("我记录数据日志");
            //LogHelper.Error("我是错误信息");
            //LogHelper.Debug("我是调试信息");

            #region 任务调度器 同步视频状态和封面

            // 从工厂中获取一个调度器实例化
            StdSchedulerFactory factory = new StdSchedulerFactory();
            IScheduler scheduler = await factory.GetScheduler();
            //开启调度器
            await scheduler.Start();
            //创建一个作业
            IJobDetail job = JobBuilder.Create<SyncVideosJob>()
                .WithIdentity("SyncVideosJob", "Video")
                .Build();
            //创建触发器
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("SyncVideosTrigger", "Video")
                .StartNow()//从现在开始执行
                .WithSimpleSchedule(m => m
                    .WithIntervalInSeconds(10)//每隔几秒执行
                    .RepeatForever())//永远重复执行
                .Build();
            await scheduler.ScheduleJob(job, trigger);

            #endregion
        }
        
        public class SyncVideosJob : IJob
        {

            /// <summary>
            /// 执行任务
            /// </summary>
            /// <param name="context"></param>
            /// <returns></returns>
            public async Task Execute(IJobExecutionContext context)
            {
                await Task.Run(() =>
                {
                    //调用BLL层更新视频的方法
                    IVideoBLL videoBLL = new VideoBLL();
                    int count = videoBLL.SyncVideos();
                    //如果更新数量>0,日志记录数量和时间 
                    if (count > 0)
                    {
                        LogHelper.Info("已同步" + count + "条数据，时间：" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                    }
                });
            }
        }
    }
}